package com.java.controller;


import com.java.domain.Users;
import com.java.service.UsersService;
import com.java.service.impl.UsersServiceImpl;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(value = "/users/*")
public class UsersServlet extends BaseServlet {
    private UsersService us =new UsersServiceImpl();
    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String uName = request.getParameter("uName");
        String pwd = request.getParameter("pwd");
        Users users = new Users();
        users.setuName(uName);
        users.setPwd(pwd);
        if (us.serveUser(users)) {
//            response.sendRedirect("../login.jsp");
            out.println(1);
        }else {
            out.println(0);
        }
    }
    public void log(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String uName = request.getParameter("uName");
        String pwd = request.getParameter("pwd");
        Users users = new Users();
        users.setuName(uName);
        users.setPwd(pwd);
        Users user = us.login(users);
        if(user!=null){
            request.getSession().setAttribute("user",user);
            out.println(1);
//            request.getRequestDispatcher("../index.jsp").forward(request,response);
        }
    }

    public void del(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().setAttribute("user",null);
        response.sendRedirect("../goods/query");
    }

    //查询用户
    public void Select(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        List<Users> usersList =  us.selectuser();
        JSONArray json= JSONArray.fromObject(usersList);
        PrintWriter out=response.getWriter();
        out.print(json);
        out.close();

    }
    //删除用户
    public void Delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out=response.getWriter();
        String  uName=request.getParameter("uName");
        int i = us.delUsers(uName);
        if(i>0){
            out.println(0);
        }else {
            out.println(1);
        }
        out.close();

    }
}
